package cn.chinaunicom.sdsi.gacx.web.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.support.json.JSONUtils;

import cn.chinaunicom.sdsi.frm.base.BaseService;
import cn.chinaunicom.sdsi.frm.sys.R;
import cn.chinaunicom.sdsi.frm.sys.entity.SysStaff;
import cn.chinaunicom.sdsi.gacx.author.dao.mybatis.AuthorMapper;
import cn.chinaunicom.sdsi.gacx.author.service.AuthorService;
import cn.chinaunicom.sdsi.gacx.common.HttpUtils;
import cn.chinaunicom.sdsi.gacx.sys.service.GaSysParamService;
import cn.chinaunicom.sdsi.gacx.sys.service.GaSysSelectLogService;
import cn.chinaunicom.sdsi.gacx.web.controller.RestServiceController;
import cn.chinaunicom.sdsi.gacx.web.service.SelectBaseInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * @author chenxl 2017/06/16
 *
 */
@Service
public class SelectBaseInfoServiceImpl extends BaseService implements
		SelectBaseInfoService {
	private final Log log = LogFactory.getLog(SelectBaseInfoServiceImpl.class);

	@Autowired
	private AuthorService authorService;
	@Autowired
	private GaSysParamService gaSysParamService;
	@Autowired
	private GaSysSelectLogService gaSysSelectLogService;

	/*
	 * 查询基本信息
	 */
	public JSONObject selectBaseInfo(Map<String, Object> requestMap) {
		ResourceBundle bundle = ResourceBundle.getBundle("upf");
		String validateElec = bundle.getString("validateElec");
		String method = (String) requestMap.get("method");
		JSONObject rObj = new JSONObject();

		String returnFlag = "0000";
		String returnInfo = "成功";

		log.debug("All param:" + JSONObject.fromObject(requestMap).toString());
		/* 公用方法校验 */
		// 工号用户ID
		if (requestMap.get("staffId") == null) {
			returnFlag = "9003";
			returnInfo = "staffId参数为空";
			log.debug(">> request param staffId is null");
		}
		// 权限号码
		if (requestMap.get("funcCode") == null) {
			returnFlag = "9004";
			returnInfo = "funcCode参数为空";
			log.debug(">> request param funcCode is null");
		}
		if (requestMap.get("ipAddr") == null) {
			returnFlag = "9005";
			returnInfo = "ipAddr参数为空";
			log.debug(">> request param ipAddr is null");
		}

		if (!returnFlag.equals("0000")) {
			rObj.element("returnFlag", returnFlag);
			rObj.element("returnInfo", returnInfo);
			return rObj;
		}

		if (validateElec.indexOf(method) != -1) {
			// 公函ID
			if (requestMap.get("elecId") == null) {
				returnFlag = "9001";
				returnInfo = "elecId参数为空";
				log.debug(">> request param elecId is null");
			}

			// 电话号码/身份证号
			/*if (requestMap.get("phoneNo") == null
					&& requestMap.get("idNo") == null) {
				returnFlag = "9002";
				returnInfo = "phoneNo/idNo参数不可全部为空";
				log.debug(">> request param phoneNo/idNo is null");
			}*/

			String elecId = (String) requestMap.get("elecId");
			String idNos = (String) requestMap.get("idNo");
			String phoneNos = (String) requestMap.get("phoneNo");
			// 获得公函校验中的身份证号
			List numList = new ArrayList();
			if(idNos!=null){
				for (String idNo : idNos.split(",")) {
					numList.add(idNo);
				}
			}
			// 获得公函校验中的电话
			if(phoneNos!=null){
				for (String phoneNo : phoneNos.split(",")) {
					numList.add(phoneNo);
				}
			}
			if (elecId.equals("")) {
				returnFlag = "9101";
				returnInfo = "公函编号不能为空";
				log.debug(">> 公函编号不能为空");
			}
			/*if (numList.size() == 0) {
				returnFlag = "9102";
				returnInfo = "查询号码列表不能为空";
				log.debug(">> 查询号码列表不能为空");
			}*/

			if (!returnFlag.equals("0000")) {
				rObj.element("returnFlag", returnFlag);
				rObj.element("returnInfo", returnInfo);
				return rObj;
			}

			// 公函校验 公函是否存在，是否超过查询有效期
			log.debug(">> elecId:" + elecId);
			rObj = authorService.canSelectCheck(elecId, numList);
			String rFlag = rObj.getString("returnFlag");
			if (!rFlag.equals("0000")) {
				returnFlag = rFlag;
				returnInfo = rObj.getString("returnInfo");
				rObj.element("returnFlag", returnFlag);
				rObj.element("returnInfo", returnInfo);
				return rObj;
			}
		}

		// String selectType = rObj.getString("selectType");
		// List sList = (List) rObj.get("phoneNo");

		/*
		 * String serviceName = ""; if (method.equals("selectBaseInfo")) { if
		 * (selectType.equals("1")) { returnFlag = "9030"; returnInfo =
		 * "公函只能按身份证查询"; } serviceName =
		 * "/gayj/frm/authorController/canSelectCheck"; }
		 */

		if (returnFlag.equals("0000")) {
			// 配置表里取公安API接口调用地址
			// String realPath =
			// gaSysParamService.getGaSysParamInfo("gayjApiAddress").getString("paramId");
			// String reqAddr = realPath + serviceName;
			// modify by yangdaobing 20170705 start

			// 获得运营管理平台Token地址
			String tokenAddress = bundle.getString("tokenAddress");

			if (StringUtils.isEmpty(tokenAddress)) {
				returnFlag = "9006";
				returnInfo = "运营管理平台Token地址不可以为空";
			} else {

				System.out.println(">>> Login json : 1024");// productId
				// 运营管理平台上获得到的用户名/密码（业务订购） 这里需要改成在properties配置的

				String userName = bundle.getString(method.concat("_username"));
				String password = bundle.getString(method.concat("_password"));
				if (StringUtils.isEmpty(userName)
						|| StringUtils.isEmpty(password)) {
					returnFlag = "9007";
					returnInfo = "运营管理平台业务订购用户名/密码不可以为空";
				} else {
					requestMap.put("username", userName);
					requestMap.put("password", password);

					log.debug(">> token address : " + tokenAddress);

					String reqParam = JSONObject.fromObject(requestMap)
							.toString();
					log.debug(">> print token reqParam = " + reqParam);
					String rspStr = "";
					try {
						//rspStr = HttpUtil.doPost(tokenAddress, reqParam);
						log.debug(">> print token result = " + rspStr);
						Map<String, String> responseObj = (Map<String, String>) JSONUtils
								.parse(rspStr);
						String loginServiceStatus = responseObj.get("status");
						String token = null;
						if ("0".equals(loginServiceStatus)) {
							// set token into session
							token = responseObj.get("token");
							log.debug(">> current token:" + token);
							log.debug(">> new token :" + token
									+ " has been got.");
						}
						// Map<String, String> paramObj = new HashMap<String,
						// String>();
						// TODO 这里是从请求参数中获取到的
						// paramObj.put("phoneNo", "18615510560");
						// paramObj.put("dataTime", "20170501");

						String reqParam1 = JSONObject.fromObject(requestMap)
								.toString();
						log.debug(">> print interface reqParam = " + reqParam1);

						String uniAddress = bundle.getString(method);
						log.debug(">> print interface address = " + uniAddress);

						// modify by yangdaobing 20170705 End
						//rspStr = HttpUtil.doPost(uniAddress, reqParam1, token);
						if (validateElec.indexOf(method) != -1) {
							// 统一日志调用服务
							gaSysSelectLogService.saveSysSelectLog(requestMap);
						}
						
						log.debug(">> add log finish.");

					} catch (Exception ex) {
						log.error(">> has an error=", ex);
						returnFlag = "9031";
						returnInfo = "调用公安大数据查询API接口异常";
					}

					rObj = JSONObject.fromObject(rspStr);
					log.debug("print rspStr ====== " + rspStr);
				}
			}
		}

		if (!returnFlag.equals("0000")) {
			rObj.element("returnFlag", returnFlag);
			rObj.element("returnInfo", returnInfo);
		}
		return rObj;
	}

	public static void main(String[] args) {
		ResourceBundle bundle = ResourceBundle.getBundle("upf");
		String method = "userVoiceQuery";
		System.err.println(bundle.getString(method));
	}

}